package org.xjtu.weteam.web.controller;

import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import org.xjtu.weteam.common.utils.FileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;

import java.io.IOException;

import java.net.URLEncoder;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;


import org.xjtu.weteam.common.JsonResponse;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.model.domain.File;

import org.xjtu.weteam.model.dto.FileDTO;
import org.xjtu.weteam.service.FileService;
import org.springframework.web.multipart.MultipartFile;



/**
 * @author Kevin
 */
@RestController
@RequestMapping("/api/file/")
public class FileController {

    @Autowired
    private FileService fileService;

    @Value("${file.upload.path:#{T(System).getProperty('user.dir')}/file/resource}")
    private String baseUploadPath;
    //TODO:改成自己的ip
    @Value("${file.base-url:http:// 192.168.12.169:8080}")
    private String baseUrl;

    // 文件大小限制（1GB）
    private static final long MAX_FILE_SIZE = 1024 * 1024 * 1024;

    @ApiOperation("文件上传")
    @PostMapping("/uploadFile")
    public JsonResponse<?> uploadFile(@RequestParam("file") MultipartFile file,
                                      @RequestHeader("X-Access-Token") String token,
                                      @RequestParam("projectId") Integer projectId,
                                      @RequestParam("fileName") String fileName) {
        try {
            // 保存文件
            String savedPath = FileUtils.saveUploadedFile(file, baseUploadPath);

            Integer userId = TokenUtils.getIdFromToken(token);

            // 保存文件信息到数据库
            File fileEntity = new File();
            fileEntity.setFileName(fileName);
            fileEntity.setFilePath(savedPath);
            fileEntity.setProjectId(projectId);

            fileEntity.setUploadedBy(userId);

            return JsonResponse.success(fileService.updateFiles(fileEntity), "文件上传成功");

        } catch (Exception e) {
            return JsonResponse.failure("文件上传失败: " + e.getMessage());
        }
    }


    @GetMapping("/listFiles")
    @ResponseBody
    public JsonResponse listFiles(Integer projectId, @RequestHeader("X-Access-Token") String token) {
        Integer userId = TokenUtils.getIdFromToken(token);
        return JsonResponse.success(fileService.listFiles(projectId, userId));
    }

    @GetMapping("/getFilePath")
    @ResponseBody
    public JsonResponse getFilePath(Integer fileId) {
        return JsonResponse.success(fileService.getFilePath(fileId));
    }

    @GetMapping("/downloadFile")
    public ResponseEntity<Resource> downloadFile(Integer fileId) throws IOException {
        File file = fileService.getFileById(fileId); // 假设有一个方法来根据文件ID查询文件

        // 获取文件在服务器上的路径
        String filePath = Paths.get(System.getProperty("user.home"), file.getFilePath().substring(1)).toString();
        Resource resource = new FileSystemResource(filePath);

        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 返回文件的响应内容
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFileName() + "\"")
                .body(resource);
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Integer fileId,
                                                 HttpServletRequest request) {
        try {
            File fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return ResponseEntity.notFound().build();
            }

            String fullPath = fileInfo.getFilePath();
            return FileUtils.generateDownloadResponse(fullPath, fileInfo.getFileName(), request);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping("/renameFile")
    @ResponseBody
    public JsonResponse renameFile(String newFileName, Integer fileId){
        return JsonResponse.success(fileService.rename(newFileName,fileId),"已重命名");
    }

    @ApiOperation("文件预览")
    @PostMapping("/preview")
    public JsonResponse<?> previewFile(Integer fileId) {
        try {
            File fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return JsonResponse.failure("文件不存在");
            }

            Map<String, Object> previewInfo = FileUtils.generatePreviewInfo(
                    fileInfo.getFileName(),
                    fileInfo.getFilePath(),
                    fileId,
                    baseUrl
            );

            return JsonResponse.success(previewInfo);

        } catch (Exception e) {
            return JsonResponse.failure("获取预览失败");
        }
    }
    @ApiOperation("删除文件")
    @PostMapping("/deleteFiles")
    public JsonResponse<?> deleteFile(Integer fileId, @RequestHeader("X-Access-Token") String token) {
        try {
            File fileInfo = fileService.getFileById(fileId);
            if (fileInfo == null) {
                return JsonResponse.failure("文件不存在");
            }

            // 验证权限
            Integer userId = TokenUtils.getIdFromToken(token);
            if (!userId.equals(fileInfo.getUploadedBy())) {
                return JsonResponse.failure("无权限删除此文件");
            }

            // 删除物理文件
            String fullPath = fileInfo.getFilePath();
            if (!FileUtils.deleteFile(fullPath)) {
                return JsonResponse.failure("物理文件删除失败");
            }

            // 删除数据库记录
            fileService.deleteFile(fileId);
            return JsonResponse.success(null, "文件删除成功");

        } catch (Exception e) {
            return JsonResponse.failure("文件删除失败: " + e.getMessage());
        }
    }

    @PostMapping("/moveFile")
    @ResponseBody
    public JsonResponse moveFile(Integer fileId, Integer projectId){
        return JsonResponse.success(fileService.moveFile(fileId, projectId));
    }
}
